package com.qf.listener;

import com.alibaba.fastjson.JSON;
import com.qf.pojo.User;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
//表示这个事务监听器监听的是哪个事务消息，和之前发送事务消息的保持一致
@RocketMQTransactionListener(txProducerGroup = "tx_group1")
public class TransactionalListener implements RocketMQLocalTransactionListener {
    /**
     * 执行本地事务
     * @param msg
     * @param arg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        try {
            byte[] bys = (byte[]) msg.getPayload();
            String json = new String(bys, "utf-8");

            User user = JSON.parseObject(json, User.class);

            //执行本地事务
            String name = user.getName();

            if ("tx1".equals(name)){
                //本地事务执行成功 -- 消息会最终发送到目标主题
                System.out.println("commit");
                return RocketMQLocalTransactionState.COMMIT;
            }else if ("tx2".equals(name)){
                //本地事务执行失败 -- 消息直接丢弃，目标主题收不到
                System.out.println("rollback");
                return RocketMQLocalTransactionState.ROLLBACK;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        //会触发生产端回查操作，1分钟一次，默认15次
        System.out.println("unknown");
        return RocketMQLocalTransactionState.UNKNOWN;
    }


    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 当本地事务返回的是一种UNKNOWN状态时，会触发
     * @param msg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        //查询数据库数据，确定本次本地事务操作最终结果

        String format = simpleDateFormat.format(new Date());
        System.out.println("回查时间:" + format);
        return RocketMQLocalTransactionState.UNKNOWN;
    }
}
